from django.contrib import admin
from .models import Collect


@admin.register(Collect)
class CollectAdmin(admin.ModelAdmin):
    """收藏管理"""
    list_display = ['id', 'user', 'attraction', 'created_at', 'get_notes_preview']
    list_display_links = ['id', 'user']
    list_filter = ['created_at', 'attraction__city']
    search_fields = ['user__username', 'attraction__name', 'notes']
    list_per_page = 20
    ordering = ['-created_at']
    raw_id_fields = ['user', 'attraction']
    date_hierarchy = 'created_at'

    def get_notes_preview(self, obj):
        """显示备注预览"""
        if obj.notes:
            return obj.notes[:50] + '...' if len(obj.notes) > 50 else obj.notes
        return '-'

    get_notes_preview.short_description = '备注预览'

    # 字段集分组
    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'attraction')
        }),
        ('收藏信息', {
            'fields': ('notes', 'created_at')
        }),
    )

    # 只读字段
    readonly_fields = ['created_at']

    # 自定义动作
    actions = ['export_collections']

    def export_collections(self, request, queryset):
        """导出收藏数据"""
        # 这里可以实现导出逻辑
        self.message_user(request, f'准备导出 {queryset.count()} 条收藏记录')

    export_collections.short_description = "导出选中的收藏记录"